//
//  AddCustomerViewController.m
//  Spa
//
//  Created by PangPond on 12/1/2556.
//  Copyright (c) พ.ศ. 2556 innova. All rights reserved.
//

#import "AddCustomerViewController.h"
#import "Customer.h"
@interface AddCustomerViewController ()

@end

@implementation AddCustomerViewController


@synthesize databaseUtility = _databaseUtility;
@synthesize keyCustomerFirstname = _keyCustomerFirstname;
@synthesize keyCustomertLastname = _keyCustomertLastname;
@synthesize keyIf;
@synthesize btnBirtday;
@synthesize tableView = _tableView;
// cell
@synthesize addCustomerFirstnameCell = _addCustomerFirstnameCell;
@synthesize fieldFirstnameCell;

@synthesize addCustomerLastname = _addCustomerLastname;
@synthesize fieldLastnameCell;

@synthesize addCustomerNickNameCell = _addCustomerNickNameCell;
@synthesize fieldNickNameCell;

@synthesize addCustomerGenderCell = _addCustomerGenderCell;

@synthesize addCustomerBirtdayCell = _addCustomerBirtdayCell;
@synthesize fieldBirtdayCell;

@synthesize addCustomerTelCell = _addCustomerTelCell;
@synthesize fieldTelCell;

@synthesize addCustomerEmailCell = _addCustomerEmailCell;
@synthesize fieldEmailCell;

@synthesize addCustomerNoteCell = _addCustomerNoteCell;
@synthesize fieldNoteCell;

- (IBAction)dismissKeyboard:(id)sender
{
	[sender resignFirstResponder];
    
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.databaseUtility = [[DatabaseUtility alloc]initWithDatabaseName:@"Database"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - UITableViewDataSource

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //[self.tableView reloadData];
    [self loadView];
    [self viewDidLoad];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 7) {
        return [AddCustomerNoteCell getCellHeight];
    }else{
        return [AddCustomerFirstnameCell getCellHeight];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 8;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray *customer = [self.databaseUtility fetchedResultsWithClass:@"Customer" withSortDescriptorString:@"firstname" withPredicateString:[NSString stringWithFormat:@"firstname == '%@'",self.keyCustomerFirstname]];
    
    Customer *customers = [customer lastObject];
    
    if (indexPath.row == 0) {
        static NSString *CellIdentifier = @"AddCustomerFirstnameCell";
        
        AddCustomerFirstnameCell *cell = (AddCustomerFirstnameCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            
            [[NSBundle mainBundle] loadNibNamed:@"AddCustomerFirstnameCell" owner:self options:nil];
            
            cell = self.addCustomerFirstnameCell;
            self.addCustomerFirstnameCell = nil;
        }
        
        //config Cell
        cell.textFieldCell.text = customers.firstname;
        return cell;
    }else if (indexPath.row == 1){
        static NSString *CellIdentifier = @"AddCustomerLastname";
        
        AddCustomerLastname *cell = (AddCustomerLastname *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            
            [[NSBundle mainBundle] loadNibNamed:@"AddCustomerLastname" owner:self options:nil];
            
            cell = self.addCustomerLastname;
            self.addCustomerLastname = nil;
        }
        
        //config Cell
        cell.textFieldCell.text = customers.lastname;
        return cell;
    }else if (indexPath.row == 2){
        static NSString *CellIdentifier = @"AddCustomerNickNameCell";
        
        AddCustomerNickNameCell *cell = (AddCustomerNickNameCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            
            [[NSBundle mainBundle] loadNibNamed:@"AddCustomerNickNameCell" owner:self options:nil];
            
            cell = self.addCustomerNickNameCell;
            self.addCustomerNickNameCell = nil;
        }
        
        //config Cell
        cell.textFieldCell.text = customers.nickname;
        return cell;
    }else if (indexPath.row == 3){
        static NSString *CellIdentifier = @"AddCustomerGenderCell";
        
        AddCustomerGenderCell *cell = (AddCustomerGenderCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            
            [[NSBundle mainBundle] loadNibNamed:@"AddCustomerGenderCell" owner:self options:nil];
            
            cell = self.addCustomerGenderCell;
            self.addCustomerGenderCell = nil;
        }
        
        //config Cell
        //cell.textFieldCell.text = customers.lastname;
        return cell;
    }else if (indexPath.row == 4){
        static NSString *CellIdentifier = @"AddCustomerBirtdayCell";
        
        AddCustomerBirtdayCell *cell = (AddCustomerBirtdayCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            
            [[NSBundle mainBundle] loadNibNamed:@"AddCustomerBirtdayCell" owner:self options:nil];
            
            cell = self.addCustomerBirtdayCell;
            self.addCustomerBirtdayCell = nil;
        }
        
        //config Cell
        cell.textFieldCell.text = customers.birtday;
        return cell;
    }else if (indexPath.row == 5){
        static NSString *CellIdentifier = @"AddCustomerTelCell";
        
        AddCustomerTelCell *cell = (AddCustomerTelCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            
            [[NSBundle mainBundle] loadNibNamed:@"AddCustomerTelCell" owner:self options:nil];
            
            cell = self.addCustomerTelCell;
            self.addCustomerTelCell = nil;
        }
        
        //config Cell
        cell.textFieldCell.text = customers.telephone;
        return cell;
    }else if (indexPath.row == 6){
        static NSString *CellIdentifier = @"AddCustomerEmailCell";
        
        AddCustomerEmailCell *cell = (AddCustomerEmailCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            
            [[NSBundle mainBundle] loadNibNamed:@"AddCustomerEmailCell" owner:self options:nil];
            
            cell = self.addCustomerEmailCell;
            self.addCustomerEmailCell = nil;
        }
        
        //config Cell
        cell.textFieldCell.text = customers.email;
        return cell;
    }else{
        static NSString *CellIdentifier = @"AddCustomerNoteCell";
        
        AddCustomerNoteCell *cell = (AddCustomerNoteCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            
            [[NSBundle mainBundle] loadNibNamed:@"AddCustomerNoteCell" owner:self options:nil];
            
            cell = self.addCustomerNoteCell;
            self.addCustomerNoteCell = nil;
        }
        
        //config Cell
        cell.textFieldCell.text = customers.note;
        return cell;
   }
    
}

-(IBAction)BackButton:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//validation

-(BOOL)validate: (NSString *) candidate{
    NSString *customerFirstname = @"[A-Z0-9a-zก-ฮ๑-๙.]{1,50}";
    
    //@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *customerFirstnames = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", customerFirstname];
    
    
    return [customerFirstnames evaluateWithObject:candidate];
}


-(IBAction)SaveButton:(id)sender{
    
    if([self validate:[fieldFirstnameCell text]] ==1)
	{
        
        if([self validate:[fieldLastnameCell text]] ==1){
            
            
            if (keyIf == @"1") {
                
                NSArray *customers = [self.databaseUtility fetchedResultsWithClass:@"Customer" withSortDescriptorString:@"firstname" withPredicateString:[NSString stringWithFormat:@"firstname == '%@'",self.keyCustomerFirstname]];
                
                Customer *customer = [customers lastObject];
                
                customer.firstname =fieldFirstnameCell.text;
                customer.lastname = fieldLastnameCell.text;
                customer.nickname =fieldNickNameCell.text;
                customer.birtday = fieldBirtdayCell.text;
                customer.telephone =fieldTelCell.text;
                customer.email = fieldEmailCell.text;
                customer.note =fieldNoteCell.text;

                [self.databaseUtility saveContext];
                [self dismissViewControllerAnimated:YES completion:nil];
                
            }else{
                
                Customer *customer = [NSEntityDescription insertNewObjectForEntityForName:@"Customer" inManagedObjectContext:self.databaseUtility.managedObjectContext];
                
                customer.firstname =fieldFirstnameCell.text;
                customer.lastname = fieldLastnameCell.text;
                customer.nickname =fieldNickNameCell.text;
                customer.birtday = fieldBirtdayCell.text;
                customer.telephone =fieldTelCell.text;
                customer.email = fieldEmailCell.text;
                customer.note =fieldNoteCell.text;

                [self.databaseUtility saveContext];
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"NO1" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert show];
        }
        
        
	}else{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"NO" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
		[alert show];
	}
}
//Animate
-(IBAction)btnb:(id)sender{
    NSLog(@"123");

        self.tableView.frame = CGRectMake(self.tableView.frame.origin.x, (self.tableView.frame.origin.y - 20 ), self.tableView.frame.size.width, self.tableView.frame.size.height);
        [UITableView commitAnimations];
    
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    NSLog(@"textFieldDidBeginEditing");
    if (textField == fieldBirtdayCell) {
        [UITableView beginAnimations:nil context:NULL];
        [UITableView setAnimationDelegate:self];
        [UITableView setAnimationDuration:0.5];
        [UITableView setAnimationBeginsFromCurrentState:YES];
        self.tableView.frame = CGRectMake(self.tableView.frame.origin.x, (self.tableView.frame.origin.y - 20 ), self.tableView.frame.size.width, self.tableView.frame.size.height);
        [UITableView commitAnimations];
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    NSLog(@"textFieldDidEndEditing");
    if (textField == fieldBirtdayCell) {
        [UITableView beginAnimations:nil context:NULL];
        [UITableView setAnimationDelegate:self];
        [UITableView setAnimationDuration:0.5];
        [UITableView setAnimationBeginsFromCurrentState:YES];
        self.tableView.frame = CGRectMake(self.tableView.frame.origin.x, (self.tableView.frame.origin.y + 20 ), self.tableView.frame.size.width, self.tableView.frame.size.height);
        [UITableView commitAnimations];
    }

}

@end
